from loaddata import modelHAFU as db

from analysis import similarity
import numpy as np
from analysis import util
import datetime
# 半全场分析


# 总进球-历史数据-数据格式化-页面显示
def getHistoryShowDatas():
    ds = db.getHistoryDataByNearYear(1)
    return ds


# 数据比对，查找相似的历史数据
def getSomeData(typedata,history,sim):
    res = {"typedata":typedata,"somelist":[]}
    somelist = []
    if typedata:
        x1 = np.array(typedata.get("data"))
        x1 = x1[[0, 4,5,8]]
        for h in history:
            if h.get("data"):
                x2 = np.array(h.get("data"))
                x2 = x2[[0,  4,5, 8]]
                r = similarity.CalSimEuD(x1, x2)
                # 相似度
                if r > sim:
                    somelist.append(h)
        res["somelist"] = somelist
    else:
        res["somelist"] = history
    return res

# 预测(根据统计信息预测)
# 返回：[统计数量,命中率,最大间隔,平均间隔,方差,当前遗漏，预测结果]
def yuchetj(tj,mzl,maxjg,avgjg,variance,crrjg,tv):
    res = [tj,mzl,maxjg,avgjg,variance,crrjg,tv]
    y = 0
    # 预测
    if tj and avgjg:
        # 转化成百分比:当前遗漏/2*平均
        n = crrjg / (variance ** (1 / 2) + avgjg)
        y = round(n, 2)
    res.append(y)
    return res

# 统计分析结果
def tjanalysisdata(ds):
    res = []
    sumres = []
    # ds : [{"info":{"matchNumStr":ds.get("matchNumStr"),"pei":0,"result":t,"sectionsNo999":sectionsNo999,"matchDate":ds.get("matchDate")},"data":[],"peid":[]}]
    # 先转化0,1格式，0表示不中，1表示中
    # 生成一个9行9列的列表
    for i in range(10):
        hang = []
        for j in range(10):
            hang.append([])
        res.append(hang)

    for i in range(10):
        hang = []
        for j in range(10):
            hang.append([])
        sumres.append(hang)

    for d in ds:
        qiu = d.get("info").get("result")
        pei = d.get("info").get("pei") - 1
        peid_qiu = d.get("peid")[pei][0]
        peid_v = d.get("peid")[pei][1]
        index = util.getHAFUindex(peid_qiu)
        res_index = util.getHAFUindex(qiu)   # 开奖
        # 赔数为行，结果为列
        for row in range(10):
            # 查找统计赔数和结果
            for h in range(10):
                if pei == row and index == h and res_index == h:
                    res[row][h].append(1)
                    sumres[row][h].append(peid_v)
                else:
                    res[row][h].append(0)
                    sumres[row][h].append(0)

    # 统计赔
    for row in range(10):
        ps = []
        qs = []
        for d in ds:
            pei = d.get("info").get("pei") - 1
            # 查找统计赔数
            if pei == row:
                ps.append(1)
            else:
                ps.append(0)
            result = d.get("info").get("result")
            qiu = util.getHAFUindex(result)
            # 查找统计结果
            if qiu == row:
                qs.append(1)
            else:
                qs.append(0)
        res[row][9] = ps
        res[9][row] = qs

    for row in range(10):
        cs = []
        for col in range(10):
            cs.append(sum(sumres[row][col]))
        sumres[row][9] = cs
    for row in range(10):
        cs = []
        for col in range(10):
            cs.append(sum(sumres[col][row]))
        sumres[9][row] = cs

    # 统计赔、球
    for i in range(10):
        for j in range(10):
            dlist = res[i][j]
            # 计算遗漏
            mzl,maxjg,avgjg,variance,crrjg = util.tj(dlist)
            # 计算总数
            tj = sum(res[i][j])
            # 计算中奖总赔率
            tv = round(sum(sumres[i][j]),2)
            # 预测根据统计信息 ,返还：[统计数量,命中率,最大间隔,平均间隔,方差,当前遗漏，总赔率，预测结果]
            yr = yuchetj(tj,mzl,maxjg,avgjg,variance,crrjg,tv)
            res[i][j] = yr
    return res

# 显示预测(s:被预测信息，tjds:历史统计数据)
def showyuche(s,tjds):
    # 保证有被预测信息
    if s:
        qp = []
        peid = s.get("peid")
        # [("s2",3.2),("s3",3.4),....]
        for i in range(len(peid)):
            qiu = util.getHAFUindex(peid[i][0])
            # (球，赔)
            qp.append((qiu,i))
        # 使用嵌套的for循环遍历二维数组
        # [统计数量, 命中率, 最大间隔, 平均间隔, 方差, 当前遗漏]

        for i in range(len(tjds)):
            row = tjds[i]
            for j in range(len(row)):
                t = (j,i)
                if t in qp:
                    tjds[i][j].append(1)
                else:
                    tjds[i][j].append(0)

        # [统计数量, 命中率, 最大间隔, 平均间隔, 方差, 当前遗漏,是否是需要预测的数据]
    return tjds

# 分析结果（tp="selling"根据正在售卖数据,其他为历史数据）
def analysis(tp,matchId,sim):
    if tp == "selling":
        s = db.getSellingData(matchId)
        h = db.getHistoryDataFromYear(2020)
    elif tp == "history":
        s = db.getHistoryDataByMatchID(matchId)
        endDay = s.get("info").get("matchDate")
        end_of_year = datetime.datetime.strptime(endDay, '%Y-%m-%d') - datetime.timedelta(days=1)
        start_of_year = end_of_year - datetime.timedelta(days=1095) - datetime.timedelta(microseconds=1)
        datestart = datetime.datetime.strftime(start_of_year, '%Y-%m-%d')
        dateend = datetime.datetime.strftime(end_of_year, '%Y-%m-%d')
        h = db.getHistoryDataBystart(datestart,dateend)
    else:
        s = None
        h = db.getHistoryDataByNearMonth(3)
    someds = getSomeData(s, h, sim)
    # tjds:9*9 的 [统计数量,命中率,最大间隔,平均间隔,方差,当前遗漏]
    tjds = tjanalysisdata(someds.get("somelist"))
    # 加上被预测的比赛信息（方便界面显示）
    tjds = showyuche(s,tjds)

    res = {"someds":someds,"tjds":tjds}
    return res



if __name__ == '__main__':
    analysis(1025835,0.31)